![]() | |
|
|
|
To access the contents, click the chapter and section titles.
Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
One common example occurs during file input. If the input routine fails, it must be sure to properly close the file. The following code shows how a routine can guard against errors and ensure that the input file is closed no matter when the error is encountered.
Private Sub LoadData(ByVal filename As String)
Dim fnum As Integer
If we fail now, the file is closed.
On Error GoTo FileOpenError
fnum = FreeFile
Open filename For Input As fnum
If we fail now, the file is open.
On Error GoTo FileReadError
Read the data from the file.
:
Close the file.
Close fnum
If we fail now, the file is closed.
On Error GoTo FileClosedError
Do any other processing that is necessary.
:
Exit Sub
FileOpenError:
Error opening the file. It is closed.
MsgBox Error & Str$(Err.Number) & _
opening file & filename & . & _
vbCrLf & Err.Description
Exit Sub
FileReadError:
Error reading from the file. It is open.
MsgBox Error & Str$(Err.Number) & _
reading file & filename & . & _
vbCrLf & Err.Description
Close the file.
Close fnum
Exit Sub
FileClosedError:
Error after the file is closed.
MsgBox Error & Str$(Err.Number) & _
processing data from file & filename & . & _
vbCrLf & Err.Description
Exit Sub
End Sub
Chapter 12, Error Handling, and Chapter 13, Standard Error Handlers, explain error handling and subroutine cleanup in greater detail. Encapsulate with VariablesA program can use variables to simplify its code. For example, if you need to use the results of a complex expression several times, calculate the expression once and save the result in a variable. Then examine the variable several times instead of reevaluating the expression each time. The following code uses the same complex expression in two places.
If ((PlayerNumber Mod 2) = 1) And (PlayerTeam = MovingTeam) Then
Do something.
:
End If
:
If ((PlayerNumber Mod 2) = 1) And (PlayerTeam = MovingTeam) Then
Do something else.
:
End If
:
The following code does the same thing without repeating the complex expression.
Dim correct_player As Boolean
correct_player = _
((PlayerNumber Mod 2) = 1) And (PlayerTeam = MovingTeam)
If correct_player Then
Do something.
:
End If
:
If correct_player Then
Do something else.
:
End If
:
This code has several advantages. It is easier to read. Assigning the expression to a well-named variable clarifies the expressions purpose. It makes the If statements easier to read and understand. It also keeps the expression in one place. If the way the program calculates the expression changes, you do not need to worry about keeping multiple copies of the expression synchronized. In many cases, evaluating the expression once also makes the code run faster. The only reason you should repeat an expression is if some value in the expression may have changed. In the previous example, if PlayerNumber changes between the If statements, the routine must reevaluate the expression. Save Property ValuesA common trick for optimizing code is to save property values in temporary variables. Accessing a variable is much faster than accessing a property. If a routine uses the property value many times, it can use a temporary variable to save time. The following example shows how a subroutine can work with a string variable instead of repeatedly accessing a text property value.
Dim car_name As String
car_name = txtCarName.Text
Work with car_name instead of txtCarName.Text.
:
Not only does this technique save time, it also makes the code easier to read. Long sequences of object references can be particularly cumbersome. The following code uses a variable to refer to an inconveniently long object expression.
Dim font_size As Single
font_size = frmPreview.picPrintPreview.Font.Size
Work with font_size instead of the long expression.
:
Use variables to simplify complex expressions and long sequences of object references. Use WithUse With statements to simplify code that uses long sequences of object references. The following code uses a With statement so it does not need to use the expression TheGame.Player(1).txtPlayerName several times.
With TheGame.Player(1).txtPlayerName
If .Text = Then
.Text = REQUIRED
.Font.Bold = True
Else
.Font.Bold = False
End If
End With
Alternatively, you could use a variable to simplify the expression as explained in the previous section. Dont Use Nested WithsNested With statements can be confusing. As the nested statements begin and end, the reader must remember which statement is in effect. The following code is legal but confusing.
Name or number but not both should be non-blank.
With TheGame.Player(1).txtPlayerName
If .Text = Then
With TheGame.Player(1).txtPlayerNumber
If .Text = Then
.Text = REQUIRED
.Font.Bold = True
Else
.Font.Bold = False
End If
End With
Else
Blank the number.
With TheGame.Player(1).txtPlayerNumber
.Text =
.Font.Bold = False
End With
End If
End With
Use temporary variables to avoid the long object expressions without using extra With statements.
Dim txt_name As TextBox
Dim txt_number As TextBox
Name or number but not both should be non-blank.
Set txt_name = TheGame.Player(1).txtPlayerName
Set txt_number = TheGame.Player(1).txtPlayerNumber
If txt_name.Text = Then
If txt_number.Text = Then
txt_number.Text = REQUIRED
txt_number.Font.Bold = True
Else
txt_number.Font.Bold = False
End If
Else
Blank txtPlayerNumber.
txt_number.Text =
txt_number.Font.Bold = False
End If
Dont Repeat CodeIf you repeat a piece of code, you need to test and debug each piece separately. You also must keep the different occurrences of the code synchronized. If you change one but forget to change another, you will introduce a bug. Rewrite the code so you use the code in only one place. This code repeats the scaling, rotating, and projection code twice.
If move_to_origin Then
Translate the object to the origin.
MoveToOrigin Polytope
Scale, rotate, and project the object.
ScaleObject Polytope, object_scale
RotateObject Polytope, object_rotation
PerspectiveProject Polytope, CenterOfProjection
Translate the back to its original position.
MoveBack Polytope
Else
Scale, rotate, and project the object.
ScaleObject Polytope, object_scale
RotateObject Polytope, object_rotation
PerspectiveProject Polytope, CenterOfProjection
End If
|
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.
|